package com.dingreading.cloud.web.util;

import javax.servlet.http.HttpServletRequest;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.UnknownHostException;

public class NetUtil {

    /**
     * 获取客户端真实IP地址（支持IPv6）
     */
    public static String getClientIpAddress(HttpServletRequest request) {
        String ip = getIpFromHeaders(request);

        if (isUnknown(ip)) {
            ip = request.getRemoteAddr();
        }

        // 处理多个IP的情况
        if (ip != null && ip.contains(",")) {
            ip = ip.split(",")[0].trim();
        }

        return normalizeIpAddress(ip);
    }

    /**
     * 从各种HTTP头中获取IP地址
     */
    private static String getIpFromHeaders(HttpServletRequest request) {
        String[] headers = {
                "X-Forwarded-For",
                "Proxy-Client-IP",
                "WL-Proxy-Client-IP",
                "HTTP_CLIENT_IP",
                "HTTP_X_FORWARDED_FOR",
                "X-Real-IP"
        };

        for (String header : headers) {
            String ip = request.getHeader(header);
            if (!isUnknown(ip)) {
                return ip;
            }
        }

        return null;
    }

    /**
     * 检查IP地址是否为unknown
     */
    private static boolean isUnknown(String ip) {
        return ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip);
    }

    /**
     * 规范化IP地址格式
     */
    private static String normalizeIpAddress(String ip) {
        if (ip == null) {
            return null;
        }

        // 处理IPv6本地回环地址
        if ("0:0:0:0:0:0:0:1".equals(ip) || "::1".equals(ip)) {
            return "127.0.0.1";
        }

        // 处理IPv6地址的格式化（可选）
        try {
            InetAddress inetAddress = InetAddress.getByName(ip);
            if (inetAddress instanceof Inet6Address) {
                // 返回规范的IPv6格式
                return inetAddress.getHostAddress();
            }
        } catch (UnknownHostException e) {
            // 如果解析失败，返回原始IP
        }

        return ip;
    }

    /**
     * 检查是否为IPv6地址
     */
    public static boolean isIPv6(String ip) {
        if (ip == null) {
            return false;
        }
        return ip.contains(":") && !ip.contains(".");
    }

    /**
     * 检查是否为IPv4地址
     */
    public static boolean isIPv4(String ip) {
        if (ip == null) {
            return false;
        }
        return ip.contains(".") && !ip.contains(":");
    }

}